package com.tubeonfire.controller;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tubeonfire.entity.Page;
import com.tubeonfire.model.PageModel;

@SuppressWarnings("serial")
public class PageServlet extends HttpServlet {

	private static final Logger log = Logger.getLogger(PageServlet.class
			.getName());

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		try {
			String[] splitted = req.getRequestURI().split("/");
			String id = "";
			if (splitted.length == 4) {
				id = splitted[2];
			} else {
				resp.sendRedirect("/home");
			}
			Page obj = PageModel.getById(id);
			if (obj != null) {
				if (obj.getType() == 1) {
					req.setAttribute("obj", obj);
					req.setAttribute("url", req.getRequestURL().toString());
					req.getRequestDispatcher("/page_content.jsp").forward(req,
							resp);
				} else {
					int page = 1;
					try {
						page = Integer.parseInt((String) req
								.getParameter("page"));
					} catch (Exception e) {
						resp.sendError(
								404,
								"This page is not exists or has been deleted ! We are sorry for the inconvenience !");
					}
					System.out.println(page);
					req.setAttribute("obj", obj);
					req.setAttribute("url", req.getRequestURL().toString());
					req.getRequestDispatcher("/page_video.jsp").forward(req,
							resp);
				}
			} else {
				resp.sendError(
						404,
						"This page is not exists or has been deleted ! We are sorry for the inconvenience !");
			}

		} catch (Exception e) {
			log.warning(e.toString());
			e.printStackTrace();
			resp.sendError(4000,
					"Website is down for maintenance. We are sorry for the inconvenience !");
		}
	}
}
